﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using DemoV5.Resources;
using System.Xml.Linq;
using System.IO;
//
using Fetion.Core;
using System.Xml;
using Fetion.Model;
using System.Security.Cryptography;
using Fetion.Util;
using ProtoBuf;
using System.Diagnostics;
namespace DemoV5
{
    public class Product
    {
        public string Name { get; set; }
        public string Category { get; set; }
    }
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
           // HttpWebRequest hwr = WebRequest.Create();
            WebClient client = new WebClient();
            string upstr = "<config>"
                          + "<client type=\"WinPhone\" version=\"2.4.0\" platform=\"Microsoft-XDeviceEmulator\" /> "
                          + "<winphone version=\"\" /> "
                          + "<user mobile-no=\""+tbUserId.Text.Trim()+"\" />"
                          + "<servers version=\"\" />"
                          + "<service-no version=\"2010-08-23 15:40:00\" />"
                          + "<parameters version=\"2011-10-11 18:26:49\" />"
                          + "<credential />"
                          + "</config>";
            client.Headers["Content-Type"] = "text/xml";
            client.Headers["Accept-Charset"] = "utf-8";
            client.Headers["Accept-Language"] = "zh-cn";
            client.UploadStringAsync(new Uri("http://221.179.173.107/mnav/getnetsystemconfig.aspx"), upstr);
            client.UploadStringCompleted += client_UploadStringCompleted;
            pwd = tbPWD.Text.Trim();
        }
        TcpChannel tc = null;
        string userid = string.Empty;
        string pwd = string.Empty;
        void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            string navStr = e.Result;
            //XElement xe = XElement.Parse(navStr);
            TextReader tr = new StringReader(navStr);
            XDocument xmldoc = XDocument.Load(tr);
            string[] ip = xmldoc.Root.Element("servers").Element("smartphone-adapter-v5").Value.Split(':');
            string host = ip[0];
            int port = int.Parse(ip[1]);
            userid = xmldoc.Element("config").Attribute("uid").Value;
            tc = new TcpChannel(new FetionFormatPackage());
            tc.Receive += tc_Receive;
            tc.Connected += tc_Connected;
            
            tc.Connect(host,port);
               
        }

        void tc_Connected(object sender, EventChannelArges e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(
               delegate
               {
                   tbResult.Text = tbResult.Text + Environment.NewLine + "连接成功!";
               });
            if (tc != null)
            {
                Reg2V5ReqArgs reg2 = new Reg2V5ReqArgs();
                reg2.platform = "Microsoft-XDeviceEmulator";
                reg2.version = "2.4.0";
                reg2.oem = "WP7.0200.0817";
                byte[] domainAndpwdSHA = MiMaHelper.SHA1("femoo.amigo.bjmcc.net" + ":" + pwd);
                byte[] useridByte = MiMaHelper.getIntegerBytes(int.Parse(userid));
                //key
                byte[] key = MiMaHelper.SHA1(MiMaHelper.mergeArrays(useridByte, domainAndpwdSHA));
                byte[] pwd_in_db=MD5Core.GetHash(key);
                string pwdStr = MiMaHelper.ToHexString(pwd_in_db);
                string clent_key_Str = MiMaHelper.ToHexString(key);

                String nonce = MiMaHelper.createNonceUseRandom();// "1DC5DE6B634AC84A749CEC6A1EE6D918";// MiMaHelper.createNonceUseRandom();
                // Pwd_Client
                byte[] Pwd_Client = MiMaHelper.SHA1(MiMaHelper.mergeArrays(useridByte, domainAndpwdSHA));
                string result = AESEncryption.Encrypt2(clent_key_Str + "%" + nonce + "%" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), pwdStr);//DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")"2013-06-19 14:58:13"
                //string result = AESEncryption.Encrypt2(MiMaHelper.ToHexString(key), MiMaHelper.ToHexString(Pwd_Client)+"%" + nonce + "%" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //string jiemaStr = AESEncryption.Decrypt2(result, pwdStr);
                reg2.response = result; //result;
                int caps=(int)(Cap.CAP_V4_DEFAULT);
                
                reg2.caps = String.Format("{0:X}", caps);
                reg2.isolateOnline = "";
                reg2.events = "1";
                reg2.userVer = "0";
                reg2.userParam = "v4default";
                reg2.status = 400;
                reg2.machineCode = "083187097023124197059220182094087142008024228072036112229171";
                reg2.clientIpAddr = "10.0.2.15";
                reg2.credentialDomains = "127.0.0.1";
                reg2.apn = 0;
                reg2.capsex = "8000";
                reg2.statistics = "imsi:310260000000000";
                reg2.contactListVersion = "0";

                //MemoryStream bodyMs = new MemoryStream();
                //Serializer.Serialize<Reg2V5ReqArgs>(bodyMs, reg2);
                //PBObject pb = new PBObject();
                //pb.userId = int.Parse(userid);
                //pb.cmd = 10102;
                //pb.body = bodyMs.GetBuffer();
                //using(MemoryStream bodyMs = new MemoryStream())
                //{
                //    Serializer.Serialize<Reg2V5ReqArgs>(bodyMs, reg2);
                //    PackageModel m = new PackageModel(int.Parse(userid), 10102, bodyMs.GetBuffer());
                //    Request<Reg2V5RspArgs> req = new Request<Reg2V5RspArgs>(m);
                //    //req.ResHandle =
                //    req.CompleteHandle = new EventHandler<ClientAsyncCompletedEventArgs<Reg2V5RspArgs>>(response);
                //    TcpChannel.AddRequest(m.Seq, req);
                //    tc.Send(req);
                //}
                SendRequest<Reg2V5ReqArgs, Reg2V5RspArgs>(reg2,
                    (object rt)=>{
                        if (rt != null)
                        {
                            //处理响应结果
                            Reg2V5RspArgs re = (Reg2V5RspArgs)rt;
                            Debug.WriteLine(re.epid);
                        }
                    }
                    );
                //Request t = new Request();
                //t.SetBody<Reg2V5ReqArgs>(int.Parse(userid), reg2);
                //Request<Reg2V5ReqArgs> req = new Request<Reg2V5ReqArgs>(int.Parse(userid),reg2);
                //tc.Send(t);
            }

        }
        public void SendRequest<Treq,Trsp>(Treq model,ResponseHandle responseHandle)
        {
            using (MemoryStream bodyMs = new MemoryStream())
            {
                Serializer.Serialize<Treq>(bodyMs, model);
                PackageModel m = new PackageModel(int.Parse(userid), 10102, bodyMs.GetBuffer());
                Request<Trsp> req = new Request<Trsp>(m);
                req.ResHandle = responseHandle;
                //req.CompleteHandle = new EventHandler<ClientAsyncCompletedEventArgs<Trsp>>((object sender, ClientAsyncCompletedEventArgs<Trsp> e) => { Debug.WriteLine(e.Result);});
                TcpChannel.AddRequest(m.Seq, req);
                tc.Send(req);
            }
        }
        void response(object sender, ClientAsyncCompletedEventArgs<Reg2V5RspArgs> e)
        {
            Debug.WriteLine(e.Result);
        }
        void tc_Receive(object sender, EventChannelReceiveArgs e)
        {
            //Product p = new Product();
            //p.Name = e.Name;
            //p.Category = e.Category;
            //List<Product> list = new List<Product>();
            //list.Add(p);

            Deployment.Current.Dispatcher.BeginInvoke(
               delegate
               {
                   tbResult.Text = tbResult.Text + Environment.NewLine + "接收成功.";
               });

        }


    }
}